package com.hunter.common.util.document;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.poi.xwpf.usermodel.Document;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;


public class WordUtils {

	
	public static void main(String[] args) {
		createTwoPic("C:\\Users\\hunter\\Desktop\\22.bmp", "C:\\Users\\hunter\\Desktop\\22.bmp", 150, 150, 
				"C:\\Users\\hunter\\Desktop\\201707251531360318.docx", "C:\\Users\\hunter\\Desktop\\201707251531360318.docx");
	}
	
	
	public static void replaceInPara(Map<String,String> map, String sourcePath, String targetPath){
		try {
			// 获得XWPFDocument对象
//			XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(templatePath));
			XWPFDocument document = new XWPFDocument(new FileInputStream(sourcePath));
			// 替换段落中的指定文字
			Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
			while (itPara.hasNext()) {
				XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
				List<XWPFRun> runs = paragraph.getRuns();
				for (XWPFRun run : runs) {
					String oneparaString = run.getText(run.getTextPosition());
					for (Map.Entry<String, String> entry : map.entrySet()) {
						oneparaString = oneparaString.replace("${"+entry.getKey()+"}", entry.getValue());
					}
					run.setText(oneparaString, 0);
				}
			}

			// 替换表格中的指定文字
			Iterator<XWPFTable> itTable = document.getTablesIterator();
			while (itTable.hasNext()) {
				XWPFTable table = (XWPFTable) itTable.next();
				int rcount = table.getNumberOfRows();
				for (int i = 0; i < rcount; i++) {
					XWPFTableRow row = table.getRow(i);
					List<XWPFTableCell> cells = row.getTableCells();
					for (XWPFTableCell cell : cells) {
						String cellTextString = cell.getText();
						for (Entry<String, String> e : map.entrySet()) {
							if (cellTextString.contains(e.getKey()))
								cellTextString = cellTextString.replace(e.getKey(), e.getValue());
						}
						cell.removeParagraph(0);
						cell.setText(cellTextString);
					}
				}
			}
			FileOutputStream outStream = null;
			outStream = new FileOutputStream(targetPath);
			document.write(outStream);
			outStream.close();
			document.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void createTwoPic(String pic1Path, String pic2Path, int width, int height, String sourcePath, String targetPath){
		try {
			// 获得XWPFDocument对象
//			XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(templatePath));
			XWPFDocument document = new XWPFDocument(new FileInputStream(sourcePath));
			// 生成图片
			XWPFParagraph p = document.createParagraph();
			XWPFRun run1 = p.createRun();
			run1.setFontFamily("宋体");
			run1.setText("保险人指纹：");
			String blipId1 = p.getDocument().addPictureData(new FileInputStream(new File(pic1Path)), Document.PICTURE_TYPE_JPEG);
			createPicture(blipId1, document.getNextPicNameNumber(Document.PICTURE_TYPE_JPEG), width, height, p);
			XWPFRun run2 = p.createRun();
			run2.setFontFamily("宋体");
			run2.setText("         见证员指纹：");
			String blipId2 = p.getDocument().addPictureData(new FileInputStream(new File(pic2Path)), Document.PICTURE_TYPE_JPEG);
			createPicture(blipId2, document.getNextPicNameNumber(Document.PICTURE_TYPE_JPEG), width, height, p);
			 
			FileOutputStream outStream = null;
			outStream = new FileOutputStream(targetPath);
			document.write(outStream);
			outStream.close();
			document.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	private static void createPicture(String blipId, int id, int width, int height,
			XWPFParagraph paragraph) {
		final int EMU = 9525;
		width *= EMU;
		height *= EMU;
		// String blipId =
		// getAllPictures().get(id).getPackageRelationship().getId();
//		if (paragraph == null) {
//			paragraph = createParagraph();
//		}
		CTInline inline = paragraph.createRun().getCTR().addNewDrawing()
				.addNewInline();
		String picXml = ""
				+ "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">"
				+ "   <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
				+ "      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
				+ "         <pic:nvPicPr>" + "            <pic:cNvPr id=\""
				+ id
				+ "\" name=\"img_"
				+ id
				+ "\"/>"
				+ "            <pic:cNvPicPr/>"
				+ "         </pic:nvPicPr>"
				+ "         <pic:blipFill>"
				+ "            <a:blip r:embed=\""
				+ blipId
				+ "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"
				+ "            <a:stretch>"
				+ "               <a:fillRect/>"
				+ "            </a:stretch>"
				+ "         </pic:blipFill>"
				+ "         <pic:spPr>"
				+ "            <a:xfrm>"
				+ "               <a:off x=\"0\" y=\"0\"/>"
				+ "               <a:ext cx=\""
				+ width
				+ "\" cy=\""
				+ height
				+ "\"/>"
				+ "            </a:xfrm>"
				+ "            <a:prstGeom prst=\"rect\">"
				+ "               <a:avLst/>"
				+ "            </a:prstGeom>"
				+ "         </pic:spPr>"
				+ "      </pic:pic>"
				+ "   </a:graphicData>" + "</a:graphic>";
		// CTGraphicalObjectData graphicData =
		// inline.addNewGraphic().addNewGraphicData();
		XmlToken xmlToken = null;
		try {
			xmlToken = XmlToken.Factory.parse(picXml);
		} catch (XmlException xe) {
			xe.printStackTrace();
		}
		inline.set(xmlToken);
		// graphicData.set(xmlToken);
		inline.setDistT(0);
		inline.setDistB(0);
		inline.setDistL(0);
		inline.setDistR(0);
		CTPositiveSize2D extent = inline.addNewExtent();
		extent.setCx(width);
		extent.setCy(height);
		CTNonVisualDrawingProps docPr = inline.addNewDocPr();
		docPr.setId(id);
		docPr.setName("docx_img_ " + id);
		docPr.setDescr("docx Picture");
	}

}